package dobest.ray.com.jiongjiong.activity.action.selftest;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.dobest.ray.corelibs.utils.ToastMgr;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import dobest.ray.com.jiongjiong.R;
import dobest.ray.com.jiongjiong.activity.BaseActivity;
import dobest.ray.com.jiongjiong.activity.action.selftest.NearVision.CheckRightEyeGuildActivity;
import dobest.ray.com.jiongjiong.utils.ACacheHelper;
import dobest.ray.com.jiongjiong.views.NavigationBar;

/**
 * Created by Ray on 2016/3/29.
 * https://github.com/ray0807
 */
public class LetterETestActivity extends BaseActivity implements View.OnClickListener, GestureDetector.OnGestureListener, OnTouchListener {


    private ImageView iv_letter_e;   //3.7                                                                                              //5.1
    private float[] LabelLengthsNear = {0.726f, 0.576f, 0.458f, 0.364f, 0.289f, 0.230f, 0.182f, 0.145f, 0.115f, 0.091f, 0.073f, 0.058f, 0.046f, 0.036f, 0.029f};
    private float[] LabelsNear = {3.7f, 3.8f, 3.9f, 4.0f, 4.1f, 4.2f, 4.3f, 4.4f, 4.5f, 4.6f, 4.7f, 4.8f, 4.9f, 5.0f, 5.1f};
    private float[] LabelLengthsFar = {7.272f, 5.776f, 4.588f, 3.645f, 2.895f, 2.3f, 1.827f, 1.451f, 1.153f, 0.916f, 0.727f, 0.578f, 0.459f, 0.364f};
    private float[] LabelsFar = {4.0f, 4.1f, 4.2f, 4.3f, 4.4f, 4.5f, 4.6f, 4.7f, 4.8f, 4.9f, 5.0f, 5.1f, 5.2f, 5.3f};
    private int[] resE = {R.mipmap.img_icon_e_up, R.mipmap.img_icon_e_down, R.mipmap.img_icon_e_left, R.mipmap.img_icon_e_right};

    private float[] LabelLength;
    private float[] Labels;

    private RelativeLayout rl_e;

    private int lenth = 0;
    private int position = 0;
    private int currentRes = 0;
    private int oldRes = 0;
    private ViewGroup.LayoutParams params;
    //1cm对应多少px
    private float cm2px;
    private int rightAn = 0;
    private int wrongAn = 0;

    private static final int COUNT_FLAG = 11;
    private static final int TEST_FINISHED = 12;
    private static final int START_NEXT = 13;
    private static final int CHANGE_IMAGE_RES = 14;

    private Context context;
    private boolean isFinished = false;
    private boolean isRight = false;
    private boolean isAllRight = false;
    private static String INTENT_IS_FAR = "INTENT_IS_FAR";
    private boolean isFarAway = false;
    private static String INTENT_IS_RIGHT = "INTENT_IS_RIGHT";
    private int brightness;

    private float endVision = 0;


    public static void startLetterETestActivity(Context context, boolean isRight, boolean isFarAway) {
        Intent intent = new Intent(context, LetterETestActivity.class);
        intent.putExtra(INTENT_IS_RIGHT, isRight);
        intent.putExtra(INTENT_IS_FAR, isFarAway);
        context.startActivity(intent);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case COUNT_FLAG:

                    break;
                case TEST_FINISHED:
                    cancleTimer();
                    navi.setTitle(isRight ? "右眼近视力检测" : "左眼近视力检测");
                    rl_e.setOnTouchListener(null);
                    if (position == 0) {
                        endVision = Labels[position];
                        ToastMgr.show("视力测试结束，眼镜视力：" + Labels[position] + "");
                    } else {
                        endVision = (isAllRight ? Labels[position] : Labels[position - 1]);
                        ToastMgr.show("视力测试结束，眼镜视力：" + (isAllRight ? Labels[position] : Labels[position - 1]) + "");
                    }
                    isFinished = true;

                    break;
                case CHANGE_IMAGE_RES:
                    currentRes = ((int) (Math.random() * 4));
                    while (oldRes == currentRes) {
                        currentRes = ((int) (Math.random() * 4));
                    }
                    iv_letter_e.setImageResource(resE[currentRes]);
                    oldRes = currentRes;
                    startTimer();//开始倒计时
                    break;
                case START_NEXT:
                    if (position < lenth - 1) {
                        position++;
                        params.width = (int) (cm2px * LabelLength[position]);
                        params.height = (int) (cm2px * LabelLength[position]);
                        iv_letter_e.setLayoutParams(params);
                        currentRes = ((int) (Math.random() * 4));
                        while (oldRes == currentRes) {
                            currentRes = ((int) (Math.random() * 4));
                        }
                        iv_letter_e.setImageResource(resE[currentRes]);
                        oldRes = currentRes;
                        startTimer();//开始倒计时
                    } else {
                        isAllRight = true;
                        handler.sendEmptyMessage(TEST_FINISHED);
                    }

                    break;

            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_letter_e_test);
        findViews();
        init();
        addListeners();
    }

    @Override
    public void findViews() {
        navi = (NavigationBar) findViewById(R.id.navi);
        navi.setBackListener(R.mipmap.img_back, "");
        navi.setTextRight("确定", this);
        navi.setTextRightColor(getResources().getColor(R.color.white));
        iv_letter_e = (ImageView) findViewById(R.id.iv_letter_e);
        rl_e = (RelativeLayout) findViewById(R.id.rl_e);
        isRight = getIntent().getBooleanExtra(INTENT_IS_RIGHT, false);
        isFarAway = getIntent().getBooleanExtra(INTENT_IS_FAR, false);

        if (isRight) {
            navi.setTitle(isFarAway ? "右眼远视力检测" : "右眼近视力检测");
        } else {
            navi.setTitle(isFarAway ? "左眼远视力检测" : "左眼近视力检测");
        }
        if (isFarAway) {
            LabelLength = LabelLengthsFar;
            Labels = LabelsFar;
        } else {
            LabelLength = LabelLengthsNear;
            Labels = LabelsNear;
        }

        try {
            brightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        Settings.System.putInt(getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS, 255);
    }

    @Override
    public void init() {
        lenth = LabelLength.length;
        params = iv_letter_e.getLayoutParams();

        cm2px = ACacheHelper.getInstance().getMesurePX(this);
        params.width = (int) (cm2px * LabelLength[position]);
        params.height = (int) (cm2px * LabelLength[position]);
        iv_letter_e.setLayoutParams(params);
        currentRes = ((int) (Math.random() * 4));
        iv_letter_e.setImageResource(resE[currentRes]);
        oldRes = currentRes;
        context = this;
    }

    @Override
    public void addListeners() {
        rl_e.setOnTouchListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_text_right:
                if (isFinished) {
                    //右眼
                    if (isRight) {
                        if (isFarAway) {
                            //远视
                            ACacheHelper.getInstance().saveFarVisionRight(this, endVision);
                        } else {
                            //近视
                            ACacheHelper.getInstance().saveNearVisionRight(this, endVision);
                        }
                        CheckRightEyeGuildActivity.startEyeGuildActivity(this, false, isFarAway);
                        finish();
                        //左眼
                    } else {
                        if (isFarAway) {
                            //远视
                            ACacheHelper.getInstance().saveFarVisionLeft(this, endVision);
                        } else {
                            //近视
                            ACacheHelper.getInstance().saveNearVisionLeft(this, endVision);
                        }
                        ToastMgr.show("视力检测结束");
                        TestResultActivity.startTestResultActivity(this, 0);
                        finish();
                    }

                } else {
                    ToastMgr.show("请先完成测试");
                }

                break;
        }
    }


    //手势监测
    //创建一个用于识别收拾的GestureDetector对象
    private GestureDetector detector = new GestureDetector(this);

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    //快速滑动
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        //velocityX表示横向的移动，根据手指移动的方向切换女孩
        if (Math.abs(velocityX) > Math.abs(velocityY)) {
            if (velocityX < 0) {
                //左
                if (currentRes == 2) {
                    rightAn++;
                    playRight();
                } else {
                    wrongAn++;
                    playWrong();
                }
            } else if (velocityX > 0) {
                //右
                if (currentRes == 3) {
                    rightAn++;
                    playRight();
                } else {
                    wrongAn++;
                    playWrong();
                }
            }
        } else {
            if (velocityY < 0) {
                //上
                if (currentRes == 0) {
                    rightAn++;
                    playRight();
                } else {
                    wrongAn++;
                    playWrong();
                }
            } else if (velocityY > 0) {
                //下
                if (currentRes == 1) {
                    rightAn++;
                    playRight();
                } else {
                    wrongAn++;
                    playWrong();
                }
            }
        }

        if (rightAn >= 3) {
            handler.sendEmptyMessage(START_NEXT);
            rightAn = 0;
            wrongAn = 0;
        } else if (wrongAn >= 3) {
            handler.sendEmptyMessage(TEST_FINISHED);
            rightAn = 0;
            wrongAn = 0;
        } else {
            handler.sendEmptyMessage(CHANGE_IMAGE_RES);
        }

        return false;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        detector.onTouchEvent(event);
        return true;
    }
    //手势监测


    private void cancleTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    //倒计时
    Timer timer;
    private int recLen = 5;

    private void startTimer() {
        recLen = 5;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timer == null) {
            timer = new Timer();
        }
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {      // UI thread
                    @Override
                    public void run() {
                        recLen--;
                        navi.setTitle("开始测试(" + recLen + "s)");
                        if (recLen < 0) {
                            handler.sendEmptyMessage(TEST_FINISHED);
                        }
                    }
                });
            }
        }, 1000, 1000);//开始倒计时
    }


    //播放音乐
    private void playRight() {
        MediaPlayer mp = new MediaPlayer();
        try {
            AssetFileDescriptor afd = getAssets().openFd("audio_di.mp3");
            mp.setDataSource(afd.getFileDescriptor());
            afd.close();
            mp.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mp.start();
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.stop();
                mp.release();
            }
        });
    }

    private void playWrong() {
        MediaPlayer mp = new MediaPlayer();
        try {
            AssetFileDescriptor afd = getAssets().openFd("audio_water_di.wav");
            mp.setDataSource(afd.getFileDescriptor());
            afd.close();
            mp.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mp.start();
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.stop();
                mp.release();
            }
        });
    }

    @Override
    protected void onDestroy() {
        Settings.System.putInt(getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS, brightness);
        super.onDestroy();
    }
}
